package com.daxia.ogmall.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.AdType;
import com.daxia.ogmall.common.MenuLevels;
import com.daxia.ogmall.common.PinguanType;
import com.daxia.ogmall.common.ProductCategoryStatus;
import com.daxia.ogmall.dto.AdDTO;
import com.daxia.ogmall.dto.AreaDesignDTO;
import com.daxia.ogmall.dto.BrandDTO;
import com.daxia.ogmall.dto.CategoryAndProductDTO;
import com.daxia.ogmall.dto.CategoryProductDTO;
import com.daxia.ogmall.dto.CityDTO;
import com.daxia.ogmall.dto.CommunityDTO;
import com.daxia.ogmall.dto.DesignDTO;
import com.daxia.ogmall.dto.DesignerDTO;
import com.daxia.ogmall.dto.HouseTypeDTO;
import com.daxia.ogmall.dto.MenuDTO;
import com.daxia.ogmall.dto.ProductCategoryDTO;
import com.daxia.ogmall.dto.ProductDTO;
import com.daxia.ogmall.dto.UserDesignDTO;
import com.daxia.ogmall.model.Product;
import com.daxia.ogmall.model.ProductCategory;
import com.daxia.ogmall.service.MenuService;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.SpringSecurityUtils;
import com.google.common.collect.Lists;

@Controller
public class IndexController extends BaseController {
	@Autowired
	private MenuService menuService;
	
	@RequestMapping(value = "/index2")
    public String index2(Map<String, Object> map) {
		prepareAds(map);
		prepareCategories(map);
		prepareOrder(map);
		prepareCommunity(map);
		prepareDesigners(map);
		prepareComunityDesign(map);
		prepareUserDesignList(map);
		prepareProducts(map);
		prepareBrands(map);
		if(null!=getCurrentUserDTO())
			request.getSession().setAttribute("ogSessionId", userService.getOgSessionId(getCurrentUserDTO().getId()));
		return "index2";
	}

    private void prepareBrands(Map<String, Object> map) {
    	BrandDTO query = new BrandDTO();
    	query.setRecommend(1);
    	
    	List<BrandDTO> brands = brandService.find(query, Page.pageSize(8));
    	map.put("brands", brands);
	}

	private void prepareProducts(Map<String, Object> map) {
		List<ProductCategoryDTO> productCategoryDTOs = Lists.newArrayList(
				productCategoryService.load(381L),
				productCategoryService.load(443L)
				);
		
		List<CategoryProductDTO> categoryProductDTOs = Lists.newArrayList();
		for (ProductCategoryDTO c : productCategoryDTOs) {
			
			CategoryProductDTO cp = new CategoryProductDTO();
			cp.setCategoryId(c.getId());
			cp.setCategoryName(c.getName());
			
			List<ProductCategory> children = c.getChildren();
			for (ProductCategory productCategory : children) {
				CategoryProductDTO cpChild = new CategoryProductDTO();
				cpChild.setCategoryId(productCategory.getId());
				cpChild.setCategoryName(productCategory.getName());
				Page p = new Page();
				p.setPageSize(8);
				cpChild.getProducts().addAll(productService.findByCategory(productCategory, p));
				
				cp.getChildren().add(cpChild);
			}
			categoryProductDTOs.add(cp);
		}
		
		map.put("categoryProductDTOs", categoryProductDTOs);
	}

	private void prepareUserDesignList(Map<String, Object> map) {
    	UserDesignDTO query = new UserDesignDTO();
    	Page page = new Page();
    	page.setPageSize(4);
    	map.put("userDesignList", userDesignService.find(query, page));
	}

	private void prepareComunityDesign(Map<String, Object> map) {
		CommunityDTO c = communityService.load(3L);
		List<HouseTypeDTO> houseTypes = designService.findDistinctHouseTypesByCommunity(c.getId());
		System.out.println(houseTypes.size());
		c.setHouseTypes(houseTypes);
		for (HouseTypeDTO ht : houseTypes) {
			List<String> areas = designService.findDistinctAreas(c.getId(), ht.getId());
			for (String area : areas) {
				DesignDTO query = new DesignDTO();
				query.setCommunity(c);
				query.setHouseType(ht);
				query.setArea(area);
				Page page = new Page();
				page.setPageSize(3);
				List<DesignDTO> designList = designService.find(query, page);
				AreaDesignDTO ad = new AreaDesignDTO();
				ad.setArea(area);
				ad.setDesignList(designList);
				ht.getAreaDesignList().add(ad);
			}
		}
		map.put("community", c);
	}

	private void prepareDesigners(Map<String, Object> map) {
    	Page page = new Page();
    	page.setPageSize(6);
    	
    	DesignerDTO query = new DesignerDTO();
    	query.setRecommend(1);
    	map.put("designerList", designerService.find(query, page));
	}

	private void prepareCommunity(Map<String, Object> map) {
    	map.put("communityList", communityService.find(new CommunityDTO(), new Page()));
	}

	private void prepareOrder(Map<String, Object> map) {
    	map.put("provinces", provinceService.findAll());
	}


	private void prepareAds(Map<String, Object> map) {
    	map.put("ads", adService.findByType(AdType.Index));	
	}

	@RequestMapping(value = "/index")
    public String index(Map<String, Object> map) {
		if (getCurrentUserDTO() != null) {
			request.getSession().setAttribute("ogSessionId", userService.getOgSessionId(getCurrentUserDTO().getId()));
		}
		if (1 == 1) {
			return "redirect:index2";
		}
    	map.put("ads", adService.findByType(AdType.Index));
    	//List<ProductCategoryDTO> categories = productCategoryService.findRoot(5);
    	List<ProductCategoryDTO> categories = productCategoryService.findAllRoot();
    	for (int i = categories.size() - 1; i >= 0; i--) {
    		ProductCategoryDTO root = categories.get(i);
			if (root.getStatus() == null || root.getStatus() == ProductCategoryStatus.Inactive.getValue()) {
				categories.remove(i);
				continue;
			}
			for (int j = root.getChildren().size() - 1; j >= 0; j--) {
				ProductCategory c = root.getChildren().get(j);
				if (c.getStatus() == null || c.getStatus() == ProductCategoryStatus.Inactive.getValue()) {
					root.getChildren().remove(j);
					continue;
				}
				
				for (int k = c.getChildren().size() - 1; k >= 0; k--) {
					ProductCategory cc = c.getChildren().get(k);
					if (cc.getStatus() == null || cc.getStatus() == ProductCategoryStatus.Inactive.getValue()) {
						c.getChildren().remove(k);
					}
				}
			}
		}
    	map.put("categories", categories);

    	Page page = new Page();
    	page.setPage(1);
    	page.setPageSize(4);
    	ProductDTO query = new ProductDTO();
    	//query.setIsNew(true);
    	//map.put("newProducts", productService.findRandom(4));
    	query.setFindByRandom(false);
    	map.put("newProducts", productService.find(query, page));
    	// product
    	
    	query = new ProductDTO();
    	query.setIsRecommend(true);
    	map.put("recommendProducts", productService.findRandom(4));
    	
    	List<BrandDTO> brands = brandService.findAll();
    	map.put("brands", brands);
    	
    	List<BrandDTO> jinkouBrands = brandService.findByTag(PinguanType.Jinkou);
    	map.put("jinkouBrands", jinkouBrands);
    	map.put("jinkouProduct", productService.findByTag(PinguanType.Jinkou));
    	
    	List<BrandDTO> dingzhiBrands = brandService.findByTag(PinguanType.Dingzhi);
    	map.put("dingzhiBrands", dingzhiBrands);
    	map.put("dingzhiProduct", productService.findByTag(PinguanType.Dingzhi));
    	
    	List<BrandDTO> pingpaiBrands = brandService.findByTag(PinguanType.Pinpai);
    	map.put("pingpaiBrands", pingpaiBrands);
    	map.put("pingpaiProduct", productService.findByTag(PinguanType.Pinpai));
    	
    	List<BrandDTO> gexingBrands = brandService.findByTag(PinguanType.Gexing);
    	map.put("gexingBrands", gexingBrands);
    	map.put("gexingProduct", productService.findByTag(PinguanType.Gexing));
    	
    	//热点城市
    	CityDTO queryCity = new CityDTO();
    	queryCity.setIsHot(true);
    	map.put("cities",cityService.find(queryCity, null));
    	
    	//推荐方案
    	List<DesignDTO> designs = designService.find(4);
    	map.put("designs", designs);
    	
    	List<CategoryAndProductDTO> cpList = new ArrayList<CategoryAndProductDTO>();
    	for (ProductCategoryDTO category : categories) {
			CategoryAndProductDTO cp = new CategoryAndProductDTO();
			cp.setCategory(category);
			cp.setChildren(category.getChildren());
			if (CollectionUtils.isNotEmpty(category.getChildren())) {
				page = new Page();
				page.setPageSize(8);
				ProductCategory firstCat = category.getChildren().get(0);
				ProductDTO queryDto = new ProductDTO();
				queryDto.setProductCategory(firstCat);
				queryDto.setIsRecommend(true);
				Page queryPage = new Page();
				queryPage.setPageSize(8);
				cp.setProducts(productService.find(queryDto, page));
			}
			page = new Page();
			page.setPageSize(3);
			AdDTO queryAd = new AdDTO();
			queryAd.setProductCategory(category);
			queryAd.setType(AdType.Category.getValue());
			List<AdDTO> adds = adService.find(queryAd, page); 
			cp.setAdds(adds);
			
			AdDTO upad = new AdDTO();
			upad.setProductCategory(category);
			upad.setType(AdType.CategoryUp.getValue());
			List<AdDTO> upAdds = adService.find(upad, page); 
			cp.setUpAds(upAdds);
			cpList.add(cp);
		}
    	
    	map.put("cpList", cpList);
        return "index";
    }
    
    @ResponseBody
    @RequestMapping(value="/changeCategory")
    public String changeCategory(Long id,Map<String, Object> map) {
    	ProductCategory category = new ProductCategoryDTO();
    	category.setId(id);
    	ProductDTO queryProduct = new ProductDTO();
    	queryProduct.setProductCategory(category);
    	queryProduct.setIsRecommend(true);
    	Page page = new Page();
    	page.setPageSize(8);
    	List<ProductDTO> products = productService.find(queryProduct, page);
    	JSONObject jObj = new JSONObject(); 
    	if(products != null && products.size() > 0) {
    		JSONArray jarray = new JSONArray(); 
    		for(ProductDTO pro:products) {
    			JSONObject proJson = new JSONObject();
    			proJson.put("id", pro.getId());
    			proJson.put("headImage", pro.getHeadImage());
    			proJson.put("name", pro.getName());
    			proJson.put("subTitle", pro.getSubTitle());
    			proJson.put("totalSold", pro.getTotalSold());
    			proJson.put("realPrice", pro.getFirstSpec().getRealPrice());
    			jarray.add(proJson); 
    		}
    		jObj.put("data", jarray);
    	} else {
    		jObj.put("data", new Vector<Product>());
    	}
    	jObj.put("success", true);
    	return jObj.toJSONString();
    }
    
    @ResponseBody
    @RequestMapping(value="/changeCity")
    public String changeCity(Long cityId,HttpServletRequest request, HttpServletResponse response) {   //切换城市
    	if(cityId == null) {
    		return createFailureInfo("选择城市信息没有传入，请重新选择...");
    	} else {
    		CityDTO city = new CityDTO();
    		city.setId(cityId);
    		city = cityService.findOne(city);
    		request.getSession().setAttribute("currentCity", city);
    		return okJson();
    	}
    }
    
    @ResponseBody
    public String createFailureInfo(String msg) {   //返回错误信息
    	JSONObject json = new JSONObject();
    	json.put("success", false);
    	json.put("msg", msg);
    	return json.toJSONString();
    }
    
	@RequestMapping(value = "/admin/index")
	public String adminIndex(Map<String, Object> map) {
		MenuDTO dto = new MenuDTO();
		dto.setLevel(MenuLevels.Level0.level());
		map.put("menus", menuService.listForAdminPage());
		map.put("user", SpringSecurityUtils.getCurrentUser());

		/*
		map.put("usersYesterday", userser);
		map.put("usersToday", value);
		
		map.put("ordersYesterday", value);
		map.put("ordersToday", value); */
		return "admin/index";
	}
	
	@RequestMapping(value = "/admin/login")
	public String adminLogin(Map<String, Object> map) {
	    if (new File("/Users/kevin/code").exists()) {
	        map.put("self", true);
	    }
		// return "admin/login";
	    return "user/login";
	}
	
	@RequestMapping(value = "/admin/form")
	public String form() {
		return "admin/form";
	}

	@RequestMapping("common_login")
	public String common_login() throws Exception {
		return "common_login";
	}
	@ResponseBody
	@RequestMapping("do_common_login")
	public String do_common_login() throws Exception {
		return "common_login";
	}
	
	@ResponseBody
	@RequestMapping("isLogined")
	public String isLogined() throws Exception {
		if (getCurrentUserDTO() != null) {
			return ok();
		} else {
			throw new RuntimeException("未登陆");
		}
	}
	
}	
